#!/usr/bin/env python
# -*-coding: utf-8 -*-
import sys
import os
import json
import psycopg2
import re
import requests
from ConfigParser import ConfigParser


ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
if ROOT_PATH not in sys.path:
    sys.path.append(ROOT_PATH)

from company_crawler.company_crawler import get_db_config

db_config = get_db_config(ROOT_PATH)

conn = psycopg2.connect(database=db_config['db'], host=db_config['host'], port=db_config['port'],
                        user=db_config['user'], password=db_config['pw'])
cur = conn.cursor()

config = ConfigParser()
with open(ROOT_PATH + '/config.cfg', 'r') as f:
    config.readfp(f)

# A股市场
def add_province_for_a_share():
    sql_select = "SELECT id, company_full_name FROM company_brief WHERE stock_id in (SELECT id from stock where stock_market NOT LIKE 'xsb%' AND alive_op=TRUE);"
    sql_update = "UPDATE company_brief SET province=%s WHERE id=%s"
    which_db = config.get('using_db', 'db_name')
    api_ip = config.get(which_db, 'apiIp')
    api_url = u'http://%s:9030/company/profile/feature?feaType=location&companyName={}&residentMapping=y' % api_ip
    cur.execute(sql_select)
    res_list = cur.fetchall()

    for res in res_list:
        try:
            html = requests.get(api_url.format(res[1]))
            html_json = json.loads(html.content)
            province = html_json.get('result', dict()).get('province', None)
            cur.execute(sql_update, (province, res[0]))
        finally:
            conn.commit()


# 新三版
def add_province_for_xsb():
    sql_select = "SELECT id, stock_code FROM stock WHERE stock_market LIKE 'xsb%' AND alive_op=TRUE"
    sql_update = "UPDATE company_brief SET province=%s WHERE stock_id=%s"
    cur.execute(sql_select)
    company_all = cur.fetchall()
    for company in company_all:
        stock_code = company[1]
        stock_id = company[0]
        try:
            province = get_province(stock_code)
            cur.execute(sql_update, (province, stock_id))
        except Exception, e:
            print e.__str__()
        finally:
            conn.commit()


def get_province(company_code):
    url = 'http://www.neeq.com.cn/nqhqController/detailCompany.do?' \
          'callback=jQuery183090558209316805_1468296293179&zqdm={}&_=1468303895153'.format(company_code)
    html = requests.get(url).content
    res_json = str_json(html)
    province = res_json['baseinfo']['area']
    if province:
        province = province.replace(u'省', u'').replace(u'市', u'')
    else:
        province = None

    return province


def str_json(html):
    json_str = re.findall('\((.+)\)', html)[0]
    json_data = json.loads(json_str)
    return json_data

def main():
    # add_province_for_a_share()
    add_province_for_xsb()

    cur.close()
    conn.close()

if __name__ == '__main__':
    main()